package ro.xblue.translator;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.db.SystemPropertyDB;


/**
 * <p>Title: Romanian AIDA</p>
 * <p>Description: :D application</p>
 * <p>Copyright: Copyright (comparator) 2003</p>
 * <p>Company: Romania Development Gateway </p>
 *
 * @author Mihai Popoaei, mihai_popoaei@yahoo.com, smike@intellisource.ro
 * @version 1.0-* @version $Id: ShowPageMessageTag.java,v 1.1 2004/10/24 23:37:03 mihaipostelnicu Exp $
 */
public class ShowPageMessageTag extends BodyTagSupport {

      private String label;
      private String hide_link;
      private String must_show_link;
      private String show_label_name;

      public String getShow_label_name () {
            return show_label_name;
      }

      public void setShow_label_name ( String show_label_name ) {
            this.show_label_name = show_label_name;
      }

      public String getMust_show_link () {
            return must_show_link;
      }

      public void setMust_show_link ( String must_show_link ) {
            this.must_show_link = must_show_link;
      }

      public String getHide_link () {
            return hide_link;
      }

      public void setHide_link ( String hide_link ) {
            this.hide_link = hide_link;
      }

      public void setLabel ( String label ) {
            this.label = label;
      }

      public String getLabel () {
            return label;
      }

      public void release () {
            super.release();
      }

      public int doEndTag () throws JspException {
      		//System.out.println("TrnLabel="+label);
            BodyContent bc = bodyContent;
            if ( bc == null && label == null ) return EVAL_PAGE;
            if ( bc != null )
                  label = bc.getString().trim();

            HttpServletRequest req = ( HttpServletRequest ) pageContext.
                  getRequest();
            HttpSession session = req.getSession( true );
            boolean show_links_flag = session.
                  getAttribute( ShowEditButtonAction.FLAG ) != null;
            ArrayList queue = ( ArrayList ) pageContext.getAttribute( PNAME_QUEUE );
            if ( queue == null ) {
                  queue = new ArrayList();
                  pageContext.setAttribute( PNAME_QUEUE, queue );
            }

            if ( show_links_flag ) {
                  if ( hide_link != null ) {
                        queue.add( label );
                  }
            } else {
                  queue.clear();
            }

            String message = "";
            if ( ( must_show_link == null ) && ( hide_link != null || ( !show_links_flag ) ) ) {
                  message = get_message( pageContext, label );
            } else {
                  if ( queue.size() > 0 ) {
                        for ( int i = 0; i < queue.size(); i++ ) {
                              String i_label = ( String ) queue.get( i );
                              message += get_linked_message( pageContext, i_label );
                        }
                        queue.clear();
                  }
                  message += get_linked_message( pageContext, label );
            }

            JspWriter writer = pageContext.getOut();
            try {
                  if ( show_label_name != null ) {
                        writer.print( label );
                        writer.print( ":" );
                  }
                  writer.print( message );
            } catch ( IOException ioEx ) {
                  System.err.println( ioEx );
            }

            this.label = null;
            this.hide_link = null;
            this.must_show_link = null;
            this.show_label_name = null;
            return EVAL_PAGE;
      }

      /**
       * result[0] = item_id
       * result[1] = item_value
       *
       * @param pageContext
       * @param label
       * @return
       */
      private static Object[] get_tr_message ( PageContext pageContext,
                                               String label ) {
            PersistenceToken token = PersistenceManager.tokenLookup( pageContext.getServletContext() );
            String def_lang = null;
            try {
                  def_lang = SystemPropertyDB.getManager( token ).getProperty( "defaultLang" );
                  if ( def_lang == null ) def_lang = "en";
            } catch ( SQLException e ) {
                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            Object bundle = pageContext.
                  getAttribute( InitLangModuleTag.PNAME_BUNDLE );
            Module_DB module = ( Module_DB ) pageContext
                  .getAttribute( InitLangModuleTag.PNAME_MODULE );
            String message = null;

            long item_id = -1;
            if ( bundle instanceof Properties ) {
                  Properties props = ( Properties ) bundle;
                  if ( props != null ) {
                        message = props.getProperty( label );
                  }
            } else if ( bundle instanceof Hashtable ) {
                  TransItem item = ( TransItem ) ( ( Hashtable ) bundle ).get( label );
                  if ( item != null ) {
                        message = item.getText();
                  } else {
                        if ( module != null ) {
                              message = module.getMessage( def_lang, label );
                        }
                        if ( message == null ) {
                              message = label;
                        }
                  }
                  if ( item != null ) {
                        item_id = item.getId();
                  }
            }

            Object[] result = new Object[]{
                  new Long( item_id ), message
            };
            return result;
      }

      public static String get_message ( PageContext pageContext,
                                         String label ) {

            if ( label == "translator.showhiddentags" ) return "";
            Object[] msg = get_tr_message( pageContext, label );
            String message = ( String ) msg[ 1 ];

            return message;
      }

      public static String get_linked_message ( PageContext pageContext,
                                                String label ) {
            if ( label == "translator.showhiddentags" ) return "";
            String module_name = ( String ) pageContext.
                  getAttribute( InitLangModuleTag.PNAME_MODULE_NAME );
            LanguageBean lang_bean = TranslatorUtils.getCurrentLanguage( ( HttpServletRequest ) pageContext.getRequest(),
                  pageContext.getServletContext() );

            Object[] msg = get_tr_message( pageContext, label );
            long item_id = ( ( Long ) msg[ 0 ] ).longValue();
            String message = ( String ) msg[ 1 ];

            StringBuffer sb = new StringBuffer().
                  append( "<a href=\"" ).
                  append( ( ( HttpServletRequest ) pageContext.getRequest() ).getContextPath() );
            if ( item_id != -1 ) {
                  sb.append( "/translator/edit_item.do?action=edit&id=" ).
                        append( item_id );
            } else {
                  sb.append( "/translator/edit_item.do?action=new" ).
                        append( "&module=" ).
                        append( module_name ).
                        append( "&label=" ).
                        append( label ).
                        append( "&dest_lang=" ).
                        append( lang_bean.language );
            }

            sb.append( "\">[E]</a>" );
            message += sb.toString();

            if ( message == null ) message = label;

            return message;
      }

      public int doStartTag () throws JspException {

            return EVAL_BODY_BUFFERED;
      }


      public static final String PNAME_QUEUE = "ro.xblue.translator.ShowPageMessageTag.QUEUE";
}
